package com.lxy_s_springboot.lxy_s_springboot.controller;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/header")
@RestController
public class HeaderController {
     //获取cookie
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        //cookie 可能为空,需要进行判断
        for (Cookie cookie:cookies) {
            System.out.println(cookie.getName()+":"+cookie.getValue());
        }
        return "获取cookie成功";
    }
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("name") String name) {
        return "从cookie中获取信息,name:"+name;
    }
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("username","zs");
        session.setAttribute("age",15);
        return "设置session成功";
    }
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        System.out.println(session.getAttribute("age"));
        return "从Session中获取信息,username "+ username;
    }
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
        String username = (String) session.getAttribute("username");
        System.out.println(session.getAttribute("age"));
        return "从Session2中获取信息,username "+ username;
    }
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("username") String username){
        return "从Session3中获取信息,username "+ username;
    }
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return "userAgent"+userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent){
        return "userAgent"+userAgent;
    }
}
